import subprocess
import re
import os
from typing import List, Dict, Any

class CompassCompareParser:
    def parse(self, text_output: str) -> List[Dict[str, Any]]:
        results = []
        current_section = None
        
        for line in text_output.splitlines():
            # 检测部分标题
            if "metric" in line:
                current_section = "metrics"
                continue
            elif "fails:runs" in line:
                current_section = "errors"
                continue
            
            # 解析数据行
            if current_section == "metrics":
                # 匹配指标行：数值A 变化百分比 数值B 指标名
                if match := re.match(r"\s*([\d.]+(?: ± \d+%)?)\s+([+-][\d.]+%)\s+([\d.]+(?: < \d+%)?)\s+(\S.+)", line):
                    results.append({
                        "type": "metric",
                        "value_a": match.group(1),
                        "change": match.group(2),
                        "value_b": match.group(3),
                        "name": match.group(4).strip()
                    })
            
            elif current_section == "errors":
                # 匹配错误行：失败:运行A 失败:运行B 错误名称
                if match := re.match(r"(\d+:\d+)\s+(\d+:\d+)\s+(.+)", line):
                    results.append({
                        "type": "error",
                        "fails_runs_a": match.group(1),
                        "fails_runs_b": match.group(2),
                        "name": match.group(3).strip()
                    })
        
        return results

class AnalysisEngine:
    def analyze_compass_results(self, group_a_ids: list, group_b_ids: list) -> List[Dict[str, Any]]:
        """验证ID数量并执行对比"""
        # 验证每组ID数量
        if len(group_a_ids) < 3 or len(group_b_ids) < 3:
            raise ValueError(
                f"Each group must have at least 3 IDs "
                f"(Group A: {len(group_a_ids)}, Group B: {len(group_b_ids)})"
            )
        
        # 执行对比命令
        id_str_a = ','.join(group_a_ids)
        id_str_b = ','.join(group_b_ids)
        cci_src = os.environ.get('CCI_SRC')
        if not cci_src:
            raise RuntimeError("环境变量 CCI_SRC 未设置，请先设置 CCI_SRC。")
        compare = cci_src+"/sbin"+"/compare"
        command = [compare, f"id={id_str_a}", f"id={id_str_b}"]
        try:
            result = subprocess.run(
                command,
                capture_output=True,
                text=True,
                check=True
            )
            # 创建解析器实例并解析结果
            parser = CompassCompareParser()
            return parser.parse(result.stdout)
        
        except subprocess.CalledProcessError as e:
            error_msg = f"Comparison failed: {e.stderr if e.stderr else e.stdout}"
            raise RuntimeError(error_msg) from e
